<!-- 模板 -->
<template>
  <div class="add-case">
    <!-- 1、导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>案例管理</el-breadcrumb-item>
      <el-breadcrumb-item>案例添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片 -->
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-alert class="fx-center" title="案例添加" :closable="false">
          </el-alert>
        </el-col>
      </el-row>
      <!-- 表单 -->
      <el-form
        :model="caseForm"
        ref="caseFormRef"
        label-position="top"
        label-width="180"
        :rules="caseFormRules"
      >
        <el-form-item label="案例名称" prop="name">
          <el-input
            v-model="caseForm.name"
            type="text"
            placeholder="输入名称"
            class="name"
            clearable
          />
        </el-form-item>
        <!-- 案例房型 -->
        <el-form-item label="案例房型" prop="houseType">
          <el-select
            class="house-type"
            v-model="caseForm.houseType"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(item, index) in houseTypeArr"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 风格 -->
        <el-form-item label="案例风格" prop="fitType">
          <el-select
            clearable
            class="fit-type"
            v-model="caseForm.fitType"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in fitTypeArr"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 面积 -->
        <el-form-item label="案例面积" prop="area">
          <el-input
            clearable
            class="area"
            v-model="caseForm.area"
            placeholder="请输入房屋面积"
          ></el-input>
        </el-form-item>
        <!-- 造价 -->
        <el-form-item label="案例造价" prop="price">
          <el-input
            clearable
            class="price"
            v-model="caseForm.price"
            placeholder="请输入工程造价"
          ></el-input>
        </el-form-item>
        <el-form-item label="案例图片">
          <el-upload
            class="upload-demo"
            action="/api/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :headers="headers"
            :before-upload="handleValid"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" :class="['el-upload__tip', ok ? '' : 'red']">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <!-- 操作 -->
        <el-form-item>
          <el-button
            class="add-btn"
            type="primary"
            @click="addCaseToList"
            icon="el-icon-search"
          >
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 3、图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="preViewDialogVisible"
      width="30%"
    >
      <img :src="preViewSrc" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import {
  priceArr,
  areaArr,
  fitTypeArr,
  houseTypeArr,
} from '../assets/js/arrays'
import { request } from '../utils/request'
import { getToken } from '../utils/token'
export default {
  name: '',
  data() {
    //定义自定义的验证规则，验证面积
    function validArae(rule, value, callback) {
      console.log(rule)
      let reg = /^\d{1,8}(\.\d{1})?$/
      if (!reg.test(value)) {
        return callback(new Error('房屋的面积必须正数,小数保留1位'))
      }
      callback()
    }
    //验证价格
    function validPrice(rule, value, callback) {
      console.log(rule)
      let reg = /^\d+$/
      if (!reg.test(value)) {
        return callback(new Error('工程造价的面积必须正整数'))
      }
      callback()
    }
    return {
      caseFormRules: {
        name: [
          { required: true, message: '请输入案例名称', trigger: 'blur' },
          {
            min: 4,
            max: 50,
            message: '长度在 4 到 50 个字符',
            trigger: 'blur',
          },
        ],
        houseType: [
          { required: true, message: '请选择房屋类型', trigger: 'change' },
        ],
        fitType: [
          { required: true, message: '请选择装修风格', trigger: 'change' },
        ],
        area: [
          { required: true, message: '请输入屋面积', trigger: 'blur' },
          { validator: validArae, trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入工程造价', trigger: 'blur' },
          { validator: validPrice, trigger: 'blur' },
        ],
      },
      ok: true,
      preViewDialogVisible: false,
      preViewSrc: '',
      caseForm: {
        houseType: '',
        fitType: '',
        area: '',
        price: '',
        name: '',
        imgs: [],
      },
      priceArr,
      areaArr,
      fitTypeArr,
      houseTypeArr,
      headers: {
        token: getToken().token,
      },
    }
  },
  computed: {
    //判断当前的数组中是否有数据
    getImgsLength() {
      return this.caseForm.imgs.length > 0
    },
    //获得当前数组最后一个元素的图片真实路径
    getImgSrc() {
      let arr = this.caseForm.imgs
      if (arr.length === 0) {
        return null
      }
      let src = 'https://www.sheli.net.cn:3009'
      let path = arr[arr.length - 1].path
      return src + path
    },
  },
  methods: {
    async addCaseToList() {
      //1、表单验证
      let form = this.$refs['caseFormRef']
      let valid = false
      try {
        valid = await form.validate()
      } catch (error) {
        console.log(error)
      }
      if (!valid) {
        return this.$message.error('请正确填写案例信息')
      }
      //2、判断图片是否上传，!!!!不能加()!!!
      if (!this.getImgsLength) {
        return this.$message.error('请上传图片信息')
      }
      //3、准备参数
      let options = {
        url: 'caselist',
        type: 'post',
        data: {
          name: this.caseForm.name,
          fitType: this.caseForm.fitType,
          houseType: this.caseForm.houseType,
          area: this.caseForm.area,
          price: this.caseForm.price,
          img: this.getImgSrc,
        },
      }
      //4、发送添加请求
      let { data: res } = await request(options)
      //5、解析返回值，判断是否成功
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success(res.msg)
      //6、成功后返回案例列表界面
      this.$router.push('/caselist')
    },
    handleValid(file) {
      console.log(file)
      if (!file) {
        return false
      }
      //验证图片格式
      let reg = /^jpg|jpeg|png$/
      //file.type = image/jpg
      let suffix = file.type.substring(file.type.lastIndexOf('/') + 1)
      if (!reg.test(suffix)) {
        this.ok = false
        this.$message.error('请上传图片')
        return false
      }
      //验证大小
      if (file.size > 500 * 1024) {
        this.ok = false
        this.$message.error('请上传500k以下的图片')
        return false
      }
      this.ok = true
      return true
    },
    handlePreview(file) {
      let path = 'https://www.sheli.net.cn:3009' + file.response.data.path
      this.preViewSrc = path
      this.preViewDialogVisible = true
    },
    handleRemove(file) {
      if (!file) {
        return
      }
      if (!file.response) {
        return
      }
      if (!file.response.data) {
        return
      }
      let path = file.response.data.path
      console.log(path)
      let index = this.caseForm.imgs.findIndex((item) => item.path === path)
      this.caseForm.imgs.splice(index, 1)
    },
    handleSuccess(res) {
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success(res.msg)
      this.caseForm.imgs.push(res.data)
    },
  },
  created() {},
  mounted() {},
}
</script>

<style lang="less" scoped>
//@import url(); 引入公共css类
.el-alert--info.is-light {
  color: #fff;
  background-color: #409eff;
}
.name,
.price,
.area,
.fit-type,
.house-type {
  width: 50%;
}
.el-form {
  margin: 0.2rem;
}
.red {
  color: red;
}
</style>
